class FertilizerPlan {
    constructor() {
        this.plans = [
            {
                id: 'plan001',
                name: '玉米生长期方案',
                status: 'active',
                progress: 65,
                startDate: '2024-03-01',
                endDate: '2024-06-30',
                cropType: '玉米',
                growthStage: '生长期',
                area: 2000,
                fertilizerTypes: [
                    { name: '复合肥', amount: 300, unit: 'kg', cost: 1200 },
                    { name: '尿素', amount: 150, unit: 'kg', cost: 750 },
                    { name: '钾肥', amount: 36, unit: 'kg', cost: 480 }
                ],
                schedule: [
                    { stage: '播种期', ratio: '30%', method: '基施' },
                    { stage: '苗期', ratio: '20%', method: '追施' },
                    { stage: '拔节期', ratio: '30%', method: '追施' },
                    { stage: '抽穗期', ratio: '20%', method: '追施' }
                ],
                notes: '根据土壤检测结果，适当增加钾肥用量'
            },
            {
                id: 'plan002',
                name: '小麦返青期方案',
                status: 'pending',
                progress: 0,
                startDate: '2024-04-01',
                endDate: '2024-07-31',
                cropType: '小麦',
                growthStage: '返青期',
                area: 1800,
                fertilizerTypes: [
                    { name: '复合肥', amount: 250, unit: 'kg', cost: 1000 },
                    { name: '尿素', amount: 120, unit: 'kg', cost: 600 }
                ],
                schedule: [
                    { stage: '返青期', ratio: '40%', method: '基施' },
                    { stage: '拔节期', ratio: '30%', method: '追施' },
                    { stage: '抽穗期', ratio: '30%', method: '追施' }
                ],
                notes: '注意气温变化，适时调整施肥时间'
            },
            {
                id: 'plan003',
                name: '棉花蕾铃期方案',
                status: 'pending',
                progress: 0,
                startDate: '2024-05-15',
                endDate: '2024-09-15',
                cropType: '棉花',
                growthStage: '蕾铃期',
                area: 2500,
                fertilizerTypes: [
                    { name: '复合肥', amount: 400, unit: 'kg', cost: 1600 },
                    { name: '尿素', amount: 180, unit: 'kg', cost: 900 },
                    { name: '磷肥', amount: 100, unit: 'kg', cost: 450 }
                ],
                schedule: [
                    { stage: '定苗期', ratio: '25%', method: '基施' },
                    { stage: '蕾期', ratio: '35%', method: '追施' },
                    { stage: '铃期', ratio: '40%', method: '追施' }
                ],
                notes: '蕾铃期注意控制氮肥用量，增施钾肥'
            },
            {
                id: 'plan004',
                name: '大豆开花期方案',
                status: 'pending',
                progress: 0,
                startDate: '2024-06-01',
                endDate: '2024-09-30',
                cropType: '大豆',
                growthStage: '开花期',
                area: 1500,
                fertilizerTypes: [
                    { name: '复合肥', amount: 200, unit: 'kg', cost: 800 },
                    { name: '钾肥', amount: 80, unit: 'kg', cost: 400 },
                    { name: '磷肥', amount: 60, unit: 'kg', cost: 300 }
                ],
                schedule: [
                    { stage: '播种期', ratio: '30%', method: '基施' },
                    { stage: '开花期', ratio: '40%', method: '追施' },
                    { stage: '结荚期', ratio: '30%', method: '追施' }
                ],
                notes: '注意磷钾肥配比，促进根瘤菌固氮'
            },
            {
                id: 'plan005',
                name: '水稻分蘖期方案',
                status: 'pending',
                progress: 0,
                startDate: '2024-05-01',
                endDate: '2024-08-31',
                cropType: '水稻',
                growthStage: '分蘖期',
                area: 3000,
                fertilizerTypes: [
                    { name: '复合肥', amount: 450, unit: 'kg', cost: 1800 },
                    { name: '尿素', amount: 200, unit: 'kg', cost: 1000 },
                    { name: '钾肥', amount: 100, unit: 'kg', cost: 500 }
                ],
                schedule: [
                    { stage: '插秧期', ratio: '20%', method: '基施' },
                    { stage: '分蘖期', ratio: '45%', method: '追施' },
                    { stage: '穗期', ratio: '35%', method: '追施' }
                ],
                notes: '水稻施肥需结合水层管理，注意防止养分流失'
            }
        ];

        this.executionHistory = [
            {
                date: '2024-03-15',
                planName: '玉米生长期方案',
                stage: '播种期',
                amount: 145.8,
                operator: '张三',
                status: 'completed'
            },
            {
                date: '2024-03-10',
                planName: '玉米生长期方案',
                stage: '播种期',
                amount: 97.2,
                operator: '李四',
                status: 'completed'
            }
        ];

        this.initializeEventListeners();
        this.updatePlanList();
        this.updateExecutionHistory();
    }

    initializeEventListeners() {
        // 监听方案列表点击
        document.getElementById('plan-list')?.addEventListener('click', (e) => {
            const planItem = e.target.closest('.plan-item');
            if (planItem) {
                const planId = planItem.dataset.planId;
                this.showPlanDetails(planId);
            }
        });

        // 监听新建方案按钮
        document.querySelector('.add-plan-btn')?.addEventListener('click', () => {
            this.showNewPlanForm();
        });

        // 监听编辑按钮
        document.querySelector('.edit-btn')?.addEventListener('click', () => {
            const activePlan = document.querySelector('.plan-item.active');
            if (activePlan) {
                this.editPlan(activePlan.dataset.planId);
            }
        });

        // 监听删除按钮
        document.querySelector('.delete-btn')?.addEventListener('click', () => {
            const activePlan = document.querySelector('.plan-item.active');
            if (activePlan) {
                this.deletePlan(activePlan.dataset.planId);
            }
        });

        // 监听历史时间范围选择
        document.getElementById('history-time-range')?.addEventListener('change', (e) => {
            this.updateExecutionHistory(e.target.value);
        });
    }

    updatePlanList() {
        const planList = document.getElementById('plan-list');
        if (!planList) return;

        planList.innerHTML = this.plans.map(plan => `
            <div class="plan-item ${plan.status === 'active' ? 'active' : ''}" data-plan-id="${plan.id}">
                <div class="plan-item-header">
                    <h4>${plan.name}</h4>
                    <span class="plan-status ${plan.status}">${plan.status === 'active' ? '执行中' : '待执行'}</span>
                </div>
                <div class="plan-item-info">
                    <div class="info-row">
                        <span class="label">作物类型：</span>
                        <span class="value">${plan.cropType}</span>
                    </div>
                    <div class="info-row">
                        <span class="label">生长阶段：</span>
                        <span class="value">${plan.growthStage}</span>
                    </div>
                    <div class="info-row">
                        <span class="label">执行周期：</span>
                        <span class="value">${plan.startDate} 至 ${plan.endDate}</span>
                    </div>
                </div>
            </div>
        `).join('');
    }

    showPlanDetails(planId) {
        const plan = this.plans.find(p => p.id === planId);
        if (!plan) return;

        const detailsContent = document.getElementById('plan-details');
        if (!detailsContent) return;

        detailsContent.innerHTML = `
            <div class="detail-section">
                <h4>基本信息</h4>
                <div class="detail-grid">
                    <div class="detail-item">
                        <span class="label">方案名称：</span>
                        <span class="value">${plan.name}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">作物类型：</span>
                        <span class="value">${plan.cropType}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">生长阶段：</span>
                        <span class="value">${plan.growthStage}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">灌溉面积：</span>
                        <span class="value">${plan.area} 平方米</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">开始日期：</span>
                        <span class="value">${plan.startDate}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">结束日期：</span>
                        <span class="value">${plan.endDate}</span>
                    </div>
                </div>
            </div>

            <div class="detail-section">
                <h4>肥料配方</h4>
                <div class="fertilizer-table">
                    <table>
                        <thead>
                            <tr>
                                <th>肥料类型</th>
                                <th>用量</th>
                                <th>单位</th>
                                <th>成本(元)</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${plan.fertilizerTypes.map(fert => `
                                <tr>
                                    <td>${fert.name}</td>
                                    <td>${fert.amount}</td>
                                    <td>${fert.unit}</td>
                                    <td>${fert.cost}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="detail-section">
                <h4>施肥进度</h4>
                <div class="schedule-timeline">
                    ${plan.schedule.map(stage => `
                        <div class="timeline-item">
                            <div class="timeline-point"></div>
                            <div class="timeline-content">
                                <h5>${stage.stage}</h5>
                                <p>比例：${stage.ratio}</p>
                                <p>方式：${stage.method}</p>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>

            <div class="detail-section">
                <h4>备注说明</h4>
                <div class="notes-content">
                    ${plan.notes}
                </div>
            </div>
        `;

        // 更新方案列表中的活动状态
        document.querySelectorAll('.plan-item').forEach(item => {
            item.classList.toggle('active', item.dataset.planId === planId);
        });
    }

    updateExecutionHistory(timeRange = '7d') {
        const historyList = document.getElementById('execution-history');
        if (!historyList) return;

        historyList.innerHTML = this.executionHistory.map(record => `
            <div class="history-item">
                <div class="history-time">${record.date}</div>
                <div class="history-info">
                    <div class="history-title">
                        <span class="plan-name">${record.planName}</span>
                        <span class="stage-name">${record.stage}</span>
                    </div>
                    <div class="history-details">
                        <span class="amount">用量：${record.amount}kg</span>
                        <span class="operator">操作人：${record.operator}</span>
                        <span class="status ${record.status}">${record.status === 'completed' ? '已完成' : '执行中'}</span>
                    </div>
                </div>
            </div>
        `).join('');

        this.updateExecutionChart(timeRange);
    }

    updateExecutionChart(timeRange) {
        const ctx = document.getElementById('executionHistoryChart');
        if (!ctx) return;

        // 模拟数据
        const data = {
            labels: ['3/10', '3/11', '3/12', '3/13', '3/14', '3/15', '3/16'],
            datasets: [{
                label: '肥料用量 (kg)',
                data: [120, 90, 110, 85, 95, 145, 97],
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }]
        };

        if (this.executionChart) {
            this.executionChart.destroy();
        }

        this.executionChart = new Chart(ctx, {
            type: 'line',
            data: data,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: '施肥执行趋势'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    showNewPlanForm() {
        // TODO: 实现新建方案表单
        alert('新建方案功能开发中...');
    }

    editPlan(planId) {
        // TODO: 实现编辑方案功能
        alert('编辑方案功能开发中...');
    }

    deletePlan(planId) {
        if (confirm('确定要删除该方案吗？')) {
            this.plans = this.plans.filter(p => p.id !== planId);
            this.updatePlanList();
            document.getElementById('plan-details').innerHTML = '';
        }
    }
}

// 创建施肥方案实例
window.fertilizerPlan = new FertilizerPlan(); 